import axios from 'axios'
import qs from 'qs'


import * as _ from '../config/tool'

// axios 配置
axios.defaults.timeout = 5000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.headers.post['x-requested-with'] = 'xmlhttprequest'; //ajax请求
axios.defaults.headers.get['x-requested-with'] = 'xmlhttprequest'; //ajax请求


axios.defaults.baseURL = 'http://yxx.feipupiano.com/weixin';

// post传参序列化
axios.interceptors.request.use((config) => {
    if (config.method === 'post') {
        config.data = qs.stringify(config.data);
    }
    return config;
}, (error) => {
    _.toast("错误的传参", 'fail');
    return Promise.reject(error);
});

// 返回状态判断
axios.interceptors.response.use((res) => {
    if (res.data.code === 50004) {
        window.location.href = res.data
    } else if (res.data.success === 'false') {
        _.toast(res.data.msg, 'fail')
    }
    // else if (res.data.success === 'true') {
    //     _.toast(res.data.msg, 'success')
    // }
    return res;
}, (error) => {
    _.toast("网络异常", 'fail');
    return Promise.reject(error);
});

export function fetch(url, params, method) {
    return new Promise((resolve, reject) => {
        if (method == 'get') {
            axios({
                url: url,
                params: params,
                method: method
            }).then(response => {
                resolve(response.data);
            }, err => {
                reject(err);
            })
                .catch((error) => {
                    reject(error)
                })
        } else if (method == 'post') {
            axios.post(url, params).then(response => {
                resolve(response.data);
            }, err => {
                reject(err);
            })
                .catch((error) => {
                    reject(error)
                })
        }
    })
}

export default {
    // 手机验证码接口
    get_mobile_code(params) {
        return fetch('/daihou/sendsms', params, 'post')
    },

    //个人信息绑定接口（卡号，身份证）
    get_userinfo_bind(params) {
        return fetch('/daihou/band', params, 'post')
    },

    //是否已绑定接口
    get_user_bind(params) {
        return fetch('/daihou/isband', params, 'post')
    },

    //该用户贷款种类接口
    get_loan_way(params) {
        return fetch('/daihou/loantype', params, 'post')
    },

    // 还款接口
    get_pay(params) {
        return fetch('/daihou/repay', params, 'post')
    },

    //变更接口
    get_change(params) {
        return fetch('/daihou/change', params, 'post')
    },

    //我要领取接口
    get_data(params) {
        return fetch('/daihou/getdata', params, 'post')
    },

    //预约日期接口
    get_appoint_date(params) {
        return fetch('/daihou/appointment', params, 'post')
    },

}